<template>
  <view class="task-type-selector">
    <u-picker
      :show="showPicker"
      :columns="typeColumns"
      @confirm="onConfirm"
      @cancel="onCancel"
      title="选择任务类型"
    />
    <u-input
      v-model="displayValue"
      :placeholder="placeholder"
      readonly
      @click="openPicker"
      class="type-input"
    />
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择任务类型'
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const showPicker = ref(false)
const selectedValue = ref(props.modelValue)

// 任务类型选项
const typeOptions = [
  { label: '常规任务', value: 'routine' },
  { label: '临时任务', value: 'temporary' },
  { label: '特殊任务', value: 'special' }
]

// 计算属性
const typeColumns = computed(() => {
  return [typeOptions]
})

const displayValue = computed(() => {
  if (!selectedValue.value) return ''
  const option = typeOptions.find(item => item.value === selectedValue.value)
  return option ? option.label : ''
})

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  selectedValue.value = newValue
})

// 方法
const openPicker = () => {
  showPicker.value = true
}

const onConfirm = (event) => {
  const selectedOption = event.value[0]
  selectedValue.value = selectedOption.value
  emit('update:modelValue', selectedOption.value)
  emit('change', selectedOption)
  showPicker.value = false
}

const onCancel = () => {
  showPicker.value = false
}
</script>

<style lang="scss" scoped>
.task-type-selector {
  .type-input {
    width: 100%;
  }
}
</style>
